package org.example.order.service;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.example.order.mapper.OrderMapper;
import org.example.order.modle.OrderInfo;
import org.example.order.modle.ProductInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

//    private static AtomicInteger atomicInteger = new AtomicInteger(1);
    private static List<ServiceInstance> instances;

//    @PostConstruct
//    public void init() {
//        instances = discoveryClient.getInstances("product-service");
//        log.info("获取实例列表: " + instances.toString());
//    }

    public OrderInfo findOrderInfoById(Integer id) {
        OrderInfo orderInfo = orderMapper.selectOrderById(id);
//        String url = "http://127.0.0.1:9090/product/" + orderInfo.getProductId();
//        List<ServiceInstance> instances = discoveryClient.getInstances("product-service");
//        log.info("获取实例列表: " + instances.toString());
//        int index = atomicInteger.getAndIncrement() % instances.size();
//        ServiceInstance serviceInstance = instances.get(index);
//        log.info("product-service 实例id: " + serviceInstance.getInstanceId());
//        String uri = serviceInstance.getUri().toString();
//        String url = uri + "/product/" + orderInfo.getProductId();
        String url = "http://product-service/product/" + orderInfo.getProductId();
        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
        orderInfo.setProductInfo(productInfo);
        return orderInfo;
    }
}
